#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright @ 2014 OPS, Qunar Inc. (qunar.com)
#
# Author: tingfang.bao <tingfang.bao@qunar.com>
# DateTime: 15-3-10 下午2:13
# 不同的子域，使用不同的app
from threading import Lock


class SubdomainDispatcher(object):
    def __init__(self, domain, create_app):
        super(SubdomainDispatcher, self).__init__()
        self.domain = domain
        self.create_app = create_app
        self.lock = Lock()
        self.instances = {}

    def get_application(self, host):
        host = host.split(':')[0]
        assert host.endswith(self.domain)
        subdomain = host[:-len(self.domain)].rstrip('.')
        with self.lock:
            print 'instances count:', len(self.instances)
            app = self.instances.get(subdomain)
            if app is None:
                app = self.create_app(subdomain)
                self.instances[subdomain] = app
            return app

    def __call__(self, environ, start_response):
        app = self.get_application(environ['HTTP_HOST'])
        return app(environ, start_response)
